package YuanFuDao2;

/**
 * 一个数组实现两个栈  ==共享栈==
 */
public class Main7 {
    public static void main(String[] args) {
        SharedStack sharedStack = new SharedStack(10);
        System.out.println(sharedStack.isEmpty(1));
        System.out.println(sharedStack.isEmpty(2));
        sharedStack.push(1,56);
        sharedStack.push(1,24);
        sharedStack.push(1,3);
        sharedStack.push(1,78);
        System.out.println(sharedStack.peek(1));
        System.out.println(sharedStack.isEmpty(1));
        System.out.println(sharedStack.isEmpty(2));
        sharedStack.push(2,67);
        sharedStack.push(2,36);
        sharedStack.push(2,7);
        sharedStack.push(2,673);
        sharedStack.push(2,66);
        sharedStack.push(2,89);
        System.out.println(sharedStack.peek(2));
        System.out.println(sharedStack.isEmpty(1));
        System.out.println(sharedStack.isEmpty(2));
        //sharedStack.push(2,892);
    }
}

class SharedStack{

    int top1;
    int top2;
    int[] nums;
    int size;
    SharedStack(int MAX_SIZE){
        top1 = -1;
        top2 = MAX_SIZE;
        size = MAX_SIZE;
        nums = new int[size];
    }

    public void push(int index,int val) {  // index == 1 表示第一个栈，index == 2表示第2个栈
        if(top2 == top1+1){
            throw new RuntimeException("栈已满");
        }else{
            if(index == 1){
                top1++;
                nums[top1] = val;
            }else if(index == 2){
                top2--;
                nums[top2] = val;
            }else{
                throw new RuntimeException("指定的栈的序号有误");
            }
        }
    }

    public int pop(int index) {
        if(index == 1){
            if(top1 > -1){
                return nums[top1--];
            }else{
                return -1;
            }
        }else{
            if(top2 < size){
                return nums[top2++];
            }else{
                return -1;
            }
        }
    }

    public int peek(int index) {
        if(index == 1){
            if(top1 > -1){
                return nums[top1];
            }else{
                return -1;
            }
        }else{
            if(top2 < size){
                return nums[top2];
            }else{
                return -1;
            }
        }
    }

    public boolean isEmpty(int index) {
        if(index == 1 && top1 == -1) return true;
        if(index == 2 && top2 == size) return true;
        return false;
    }

}
